package cn.tedu.jxc.repo.impl;

import cn.tedu.jxc.pojo.vo.CategoryListItemVO;
import cn.tedu.jxc.repo.CategoryRedisRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import javax.xml.soap.SAAJResult;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

@Slf4j
@Repository
public class CategoryRedisRepositoryImpl implements CategoryRedisRepository {
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public void saveList(List<CategoryListItemVO> categoryListItemVOS) {
        String key = CATEGORY_LIST_KEY;
        for (CategoryListItemVO categoryListItemVO : categoryListItemVOS) {
            redisTemplate.opsForList().rightPush(key,categoryListItemVO);
        }
        redisTemplate.opsForSet().add(CATEGORY_KEYS_KEY, key);

    }

    @Override
    public List<CategoryListItemVO> getList() {
       return getListRange(0L,-1L);
    }

    @Override
    public List<CategoryListItemVO> getListRange(Long start, Long end) {
        String key = CATEGORY_LIST_KEY;
        List<Serializable> lists = redisTemplate.opsForList().range(key, start, end);
        List<CategoryListItemVO> categoryListItemVOS = new ArrayList<>();
        for (Serializable range : lists) {
            categoryListItemVOS.add((CategoryListItemVO) range);
        }
        return categoryListItemVOS;
    }

    @Override
    public void deleteAll() {
        String key = CATEGORY_KEYS_KEY;
        Set<Serializable> members = redisTemplate.opsForSet().members(key);
        Collection<String> collection = new ArrayList<>();
        for (Serializable member : members) {
            collection.add((String) member);
        }
        collection.add(key);
        redisTemplate.delete(collection);
    }
}
